<template>
  <div class="commission-detail">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>积分明细</h2>
      <p class="page-description">商户分佣明细，包含广告分佣与异业分佣</p>
    </div>

    <!-- 积分统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <i class="el-icon-coin stat-icon points-icon"></i>
            <div class="stat-content">
              <div class="stat-label">总积分值</div>
              <div class="stat-value points-value">{{ formatPoints(statistics.totalPoints) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <i class="el-icon-wallet stat-icon balance-icon"></i>
            <div class="stat-content">
              <div class="stat-label">可兑换余额</div>
              <div class="stat-value balance-value">¥{{ formatAmount(statistics.availablePoints) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分佣明细表格 -->
    <el-card shadow="never" class="table-card">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-document"></i>
          分佣明细
        </span>
        <div class="filter-controls">
          <el-select
            v-model="searchForm.type"
            placeholder="分佣类型"
            clearable
            style="width: 150px; margin-right: 10px;"
            @change="handleSearch">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="广告分佣" :value="1"></el-option>
            <el-option label="异业分佣" :value="2"></el-option>
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 240px; margin-right: 10px;"
            @change="handleSearch">
          </el-date-picker>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </div>
      </div>

      <!-- 积分明细列表 -->
      <configurable-table
        :columns="tableColumns"
        :data="pointsList"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        :page-sizes="[10, 20, 30, 50]"
        pagination-layout="total, sizes, prev, pager, next, jumper"
        @page-change="handlePageChange"
        stripe
        style="width: 100%">
        <!-- 分佣类型列 -->
        <template slot="type" slot-scope="{ row }">
          <el-tag :type="row.type === 1 ? 'success' : 'warning'">
            {{ row.type === 1 ? '广告分佣' : '异业分佣' }}
          </el-tag>
        </template>
        <!-- 积分变动列 -->
        <template slot="points" slot-scope="{ row }">
          <span class="points-increase">+{{ row.points }}</span>
        </template>
        <!-- 金额变动列 -->
        <template slot="amount" slot-scope="{ row }">
          <span class="amount-increase">+¥{{ formatAmount(row.amount) }}</span>
        </template>
        <!-- 关联订单列 -->
        <template slot="orderId" slot-scope="{ row }">
          {{ row.orderId || '-' }}
        </template>
        <!-- 描述列 -->
        <template slot="description" slot-scope="{ row }">
          {{ row.description || '-' }}
        </template>
        <!-- 创建时间列 -->
        <template slot="createTime" slot-scope="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
        <!-- 操作列 -->
        <template slot="actions" slot-scope="{ row }">
          <el-button
            type="text"
            size="small"
            @click="handleView(row)">
            查看
          </el-button>
        </template>
      </configurable-table>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="积分明细详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      custom-class="view-dialog">
      <el-descriptions :column="1" border v-if="currentDetail">
        <el-descriptions-item label="记录ID">
          {{ currentDetail.id }}
        </el-descriptions-item>
        <el-descriptions-item label="分佣类型">
          <el-tag :type="currentDetail.type === 1 ? 'success' : 'warning'">
            {{ currentDetail.type === 1 ? '广告分佣' : '异业分佣' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="积分变动">
          <span class="points-increase" style="font-size: 16px; font-weight: bold;">
            +{{ currentDetail.points }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="金额变动">
          <span class="amount-increase" style="font-size: 16px; font-weight: bold;">
            +¥{{ formatAmount(currentDetail.amount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="关联订单">
          {{ currentDetail.orderId || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          {{ currentDetail.description || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="分佣比例" v-if="currentDetail.proportion">
          {{ (currentDetail.proportion * 100).toFixed(2) }}%
        </el-descriptions-item>
        <el-descriptions-item label="账期" v-if="currentDetail.period">
          {{ currentDetail.period }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentDetail.createTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import request from '@/utils/request'

export default {
  name: 'CommissionDetail',
  data() {
    return {
      // 账户统计信息
      statistics: {
        totalPoints: 0,
        availablePoints: 0
      },
      // 积分明细列表
      pointsList: [],
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '记录ID', minWidth: 100, align: 'center' },
        { prop: 'type', label: '分佣类型', minWidth: 120, align: 'center', slot: 'type' },
        { prop: 'points', label: '积分变动', minWidth: 120, align: 'center', slot: 'points' },
        { prop: 'amount', label: '金额变动', minWidth: 120, align: 'center', slot: 'amount' },
        { prop: 'orderId', label: '关联订单', minWidth: 150, slot: 'orderId', showOverflowTooltip: true },
        { prop: 'description', label: '描述', minWidth: 180, slot: 'description', showOverflowTooltip: true },
        { prop: 'createTime', label: '创建时间', minWidth: 160, align: 'center', slot: 'createTime' },
        { label: '操作', minWidth: 100, align: 'center', slot: 'actions', fixed: 'right' }
      ],
      // 查询表单
      searchForm: {
        type: null,
        startTime: '',
        endTime: ''
      },
      // 日期范围
      dateRange: [],
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 加载状态
      loading: false,
      // 详情对话框
      detailDialogVisible: false,
      currentDetail: null
    }
  },
  created() {
    this.loadStatistics()
    this.loadData()
  },
  methods: {

    // 加载账户统计信息
    async loadStatistics() {
      try {
        Logger.log('=== 开始加载商家账户详情 ===')
        const userId = this.$store.state.user.id
        Logger.log('商家用户ID:', userId)

        // 使用 /agg/account/detail 接口获取账户信息
        const response = await request({
          url: '/agg/account/detail',
          method: 'get',
          params: userId ? { userId } : {}
        })

        Logger.log('账户详情接口响应:', response)

        if (response && response.code === 0) {
          const data = response.data

          // 设置账户统计信息
          this.statistics = {
            totalPoints: data.pointBalance || 0,
            availablePoints: data.balance || 0  // balance 是可提现金额
          }

          Logger.log('账户统计信息加载成功:', this.statistics)
        } else {
          Logger.error('账户详情接口返回错误:', response)
          Message.error(response?.msg || '加载账户详情失败')
        }
      } catch (error) {
        Logger.error('=== 加载账户详情失败 ===')
        Logger.error('错误信息:', error)
        Message.error('加载账户详情失败: ' + error.message)
      }
    },

    // 加载积分明细列表
    async loadData() {
      this.loading = true
      try {
        Logger.log('=== 开始加载积分明细列表 ===')
        Logger.log('查询参数:', this.searchForm)
        Logger.log('分页参数:', this.pagination)

        // 使用 /agg/point/page 接口
        const params = {
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
          userId: this.$store.state.user.id
        }

        // 添加平台参数（区分广告分佣和异业分佣）
        if (this.searchForm.type !== null) {
          params.platform = this.searchForm.type // 1-广告分佣, 2-异业分佣
        }

        // 添加日期范围参数
        if (this.searchForm.startTime) {
          params.startTime = this.searchForm.startTime
        }
        if (this.searchForm.endTime) {
          params.endTime = this.searchForm.endTime
        }

        Logger.log('调用积分明细接口，参数:', params)

        const response = await request({
          url: '/agg/point/page',
          method: 'post',
          data: params
        })

        Logger.log('积分明细接口响应:', response)

        if (response && response.code === 0) {
          const data = response.data
          this.pointsList = data.list || []
          this.pagination.total = data.total || 0
          Logger.log('积分明细加载成功，共', this.pagination.total, '条记录')
        } else {
          Logger.error('积分明细接口返回错误:', response)
          Message.error(response?.msg || '加载积分明细失败')
          this.pointsList = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('=== 加载积分明细失败 ===')
        Logger.error('错误信息:', error)
        Message.error('加载积分明细失败: ' + error.message)
        this.pointsList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 格式化积分（保留2位小数）
    formatPoints(points) {
      if (points === undefined || points === null) return '0.00'
      return Number(points).toFixed(2)
    },

    // 格式化金额（分转元）
    formatAmount(amount) {
      if (amount === undefined || amount === null) return '0.00'
      // 如果金额大于等于100或为负数，假设是以分为单位
      if (Math.abs(amount) >= 100) {
        return (amount / 100).toFixed(2)
      }
      return Number(amount).toFixed(2)
    },

    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return '-'
      return datetime.replace('T', ' ').slice(0, 19)
    },

    // 查看详情
    handleView(row) {
      this.currentDetail = { ...row }
      this.detailDialogVisible = true
    },

    // 查询
    handleSearch() {
      // 更新日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.searchForm.startTime = this.dateRange[0]
        this.searchForm.endTime = this.dateRange[1]
      } else {
        this.searchForm.startTime = ''
        this.searchForm.endTime = ''
      }

      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        type: null,
        startTime: '',
        endTime: ''
      }
      this.dateRange = []
      this.pagination.current = 1
      this.loadData()
    },

    // 分页改变（兼容 ConfigurableTable 的 page-change 事件）
    handlePageChange({ currentPage, pageSize }) {
      this.pagination.current = currentPage
      this.pagination.size = pageSize
      this.loadData()
    }
  }
}
</script>

<style scoped>
.commission-detail {
  padding: 20px;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 统计卡片 */
.statistics {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-card >>> .el-card__body {
  padding: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 48px;
  margin-right: 20px;
}

.points-icon {
  color: #E6A23C;
}

.balance-icon {
  color: #67C23A;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.points-value {
  color: #E6A23C;
}

.balance-value {
  color: #67C23A;
}

/* 表格卡片 */
.table-card >>> .el-card__body {
  padding: 20px;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.card-title i {
  margin-right: 5px;
}

.filter-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 积分/金额变动样式 */
.points-increase {
  color: #67C23A;
  font-weight: bold;
}

.amount-increase {
  color: #67C23A;
  font-weight: bold;
}

/* 表格样式 */
.el-table {
  width: 100% !important;
}

.el-table th,
.el-table td {
  padding: 12px 8px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 详情对话框 */
/* 对话框底部样式已移至公共样式 dialog.scss */

/* 功能暂未开放样式 */
.feature-unavailable {
  padding: 40px 20px;
}

.alert-content {
  line-height: 1.6;
}

.alert-content p {
  margin: 8px 0;
}

.placeholder-content {
  margin-top: 30px;
  text-align: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  border: 1px solid #e4e7ed;
}

.placeholder-icon {
  font-size: 64px;
  color: #409eff;
  margin-bottom: 20px;
}

.placeholder-text h3 {
  color: #303133;
  margin: 0 0 15px 0;
  font-size: 20px;
}

.placeholder-text p {
  color: #606266;
  margin: 10px 0;
  font-size: 14px;
}

.placeholder-text ul {
  text-align: left;
  display: inline-block;
  margin: 20px 0;
  color: #606266;
}

.placeholder-text li {
  margin: 8px 0;
  position: relative;
  padding-left: 20px;
}

.placeholder-text li::before {
  content: "✓";
  position: absolute;
  left: 0;
  color: #67c23a;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .statistics .el-col {
    margin-bottom: 10px;
  }

  .filter-controls {
    width: 100%;
    margin-top: 10px;
  }

  .filter-controls .el-select,
  .filter-controls .el-date-picker {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .placeholder-content {
    padding: 20px 15px;
  }

  .placeholder-icon {
    font-size: 48px;
  }
}
</style>
